<?php
require_once 'config.php';

// 检查用户是否已登录
if (!isLoggedIn()) {
    $_SESSION['flash_message'] = "请先登录后再查看借阅记录";
    $_SESSION['flash_type'] = "warning";
    redirect('login.php');
}

// 获取当前用户ID
$user_id = $_SESSION['user_id'];

// 处理归还图书请求
if (isset($_POST['return_book']) && isset($_POST['borrow_id'])) {
    $borrow_id = (int)$_POST['borrow_id'];
    
    try {
        // 开始事务
        $pdo->beginTransaction();
        
        // 获取借阅记录
        $stmt = $pdo->prepare("SELECT b.*, bk.title, bk.book_id FROM borrowings b 
                              JOIN books bk ON b.book_id = bk.book_id 
                              WHERE b.borrow_id = ? AND b.user_id = ? AND b.status = 'borrowed'");
        $stmt->execute([$borrow_id, $user_id]);
        $borrowing = $stmt->fetch();
        
        if (!$borrowing) {
            $pdo->rollBack();
            $_SESSION['flash_message'] = "未找到有效的借阅记录";
            $_SESSION['flash_type'] = "danger";
        } else {
            // 更新借阅状态
            $stmt = $pdo->prepare("UPDATE borrowings SET status = 'returned', actual_return_date = CURRENT_DATE() WHERE borrow_id = ?");
            $stmt->execute([$borrow_id]);
            
            // 更新图书可借数量
            $stmt = $pdo->prepare("UPDATE books SET available = available + 1 WHERE book_id = ?");
            $stmt->execute([$borrowing['book_id']]);
            
            $pdo->commit();
            
            $_SESSION['flash_message'] = "《{$borrowing['title']}》已成功归还";
            $_SESSION['flash_type'] = "success";
        }
    } catch(PDOException $e) {
        $pdo->rollBack();
        $_SESSION['flash_message'] = "归还失败: " . $e->getMessage();
        $_SESSION['flash_type'] = "danger";
    }
}

// 获取借阅记录
try {
    // 查询当前借阅
    $stmt = $pdo->prepare("SELECT b.*, bk.title, bk.author FROM borrowings b 
                          JOIN books bk ON b.book_id = bk.book_id 
                          WHERE b.user_id = ? AND b.status = 'borrowed' 
                          ORDER BY b.borrow_date DESC");
    $stmt->execute([$user_id]);
    $current_borrowings = $stmt->fetchAll();
    
    // 查询历史借阅
    $stmt = $pdo->prepare("SELECT b.*, bk.title, bk.author FROM borrowings b 
                          JOIN books bk ON b.book_id = bk.book_id 
                          WHERE b.user_id = ? AND b.status = 'returned' 
                          ORDER BY b.actual_return_date DESC");
    $stmt->execute([$user_id]);
    $history_borrowings = $stmt->fetchAll();
    
    // 查询逾期借阅
    $stmt = $pdo->prepare("SELECT b.*, bk.title, bk.author FROM borrowings b 
                          JOIN books bk ON b.book_id = bk.book_id 
                          WHERE b.user_id = ? AND b.status = 'borrowed' AND b.return_date < CURRENT_DATE() 
                          ORDER BY b.return_date ASC");
    $stmt->execute([$user_id]);
    $overdue_borrowings = $stmt->fetchAll();
} catch(PDOException $e) {
    $_SESSION['flash_message'] = "获取借阅记录失败: " . $e->getMessage();
    $_SESSION['flash_type'] = "danger";
    $current_borrowings = [];
    $history_borrowings = [];
    $overdue_borrowings = [];
}

// 页面标题
$page_title = "我的借阅 - 图书借阅系统";

// 引入头部
include 'header.php';
?>

<h2 class="mb-4">我的借阅</h2>

<ul class="nav nav-tabs mb-4" id="borrowingTabs" role="tablist">
    <li class="nav-item">
        <a class="nav-link active" id="current-tab" data-toggle="tab" href="#current" role="tab" aria-controls="current" aria-selected="true">
            当前借阅 <span class="badge badge-primary"><?php echo count($current_borrowings); ?></span>
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" id="history-tab" data-toggle="tab" href="#history" role="tab" aria-controls="history" aria-selected="false">
            借阅历史 <span class="badge badge-secondary"><?php echo count($history_borrowings); ?></span>
        </a>
    </li>
    <?php if (!empty($overdue_borrowings)): ?>
        <li class="nav-item">
            <a class="nav-link text-danger" id="overdue-tab" data-toggle="tab" href="#overdue" role="tab" aria-controls="overdue" aria-selected="false">
                逾期未还 <span class="badge badge-danger"><?php echo count($overdue_borrowings); ?></span>
            </a>
        </li>
    <?php endif; ?>
</ul>

<div class="tab-content" id="borrowingTabsContent">
    <!-- 当前借阅 -->
    <div class="tab-pane fade show active" id="current" role="tabpanel" aria-labelledby="current-tab">
        <?php if (empty($current_borrowings)): ?>
            <div class="alert alert-info">
                您当前没有借阅任何图书
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>图书名称</th>
                            <th>作者</th>
                            <th>借阅日期</th>
                            <th>应还日期</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($current_borrowings as $borrowing): ?>
                            <tr>
                                <td>
                                    <a href="book_detail.php?id=<?php echo $borrowing['book_id']; ?>">
                                        <?php echo htmlspecialchars($borrowing['title']); ?>
                                    </a>
                                </td>
                                <td><?php echo htmlspecialchars($borrowing['author']); ?></td>
                                <td><?php echo date('Y-m-d', strtotime($borrowing['borrow_date'])); ?></td>
                                <td>
                                    <?php 
                                    $return_date = strtotime($borrowing['return_date']);
                                    $today = time();
                                    $days_left = ceil(($return_date - $today) / (60 * 60 * 24));
                                    
                                    echo date('Y-m-d', $return_date);
                                    
                                    if ($days_left < 0) {
                                        echo ' <span class="badge badge-danger">逾期 ' . abs($days_left) . ' 天</span>';
                                    } elseif ($days_left <= 3) {
                                        echo ' <span class="badge badge-warning">剩余 ' . $days_left . ' 天</span>';
                                    }
                                    ?>
                                </td>
                                <td>
                                    <span class="badge badge-primary">借阅中</span>
                                </td>
                                <td>
                                    <form method="post" action="" style="display: inline;">
                                        <input type="hidden" name="borrow_id" value="<?php echo $borrowing['borrow_id']; ?>">
                                        <button type="submit" name="return_book" class="btn btn-sm btn-success" onclick="return confirm('确定要归还《<?php echo htmlspecialchars($borrowing['title']); ?>》吗？')">
                                            归还
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
    
    <!-- 借阅历史 -->
    <div class="tab-pane fade" id="history" role="tabpanel" aria-labelledby="history-tab">
        <?php if (empty($history_borrowings)): ?>
            <div class="alert alert-info">
                您暂无借阅历史记录
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>图书名称</th>
                            <th>作者</th>
                            <th>借阅日期</th>
                            <th>归还日期</th>
                            <th>状态</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($history_borrowings as $borrowing): ?>
                            <tr>
                                <td>
                                    <a href="book_detail.php?id=<?php echo $borrowing['book_id']; ?>">
                                        <?php echo htmlspecialchars($borrowing['title']); ?>
                                    </a>
                                </td>
                                <td><?php echo htmlspecialchars($borrowing['author']); ?></td>
                                <td><?php echo date('Y-m-d', strtotime($borrowing['borrow_date'])); ?></td>
                                <td><?php echo date('Y-m-d', strtotime($borrowing['actual_return_date'])); ?></td>
                                <td>
                                    <span class="badge badge-success">已归还</span>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
    
    <!-- 逾期未还 -->
    <?php if (!empty($overdue_borrowings)): ?>
        <div class="tab-pane fade" id="overdue" role="tabpanel" aria-labelledby="overdue-tab">
            <div class="alert alert-danger mb-4">
                您有 <?php echo count($overdue_borrowings); ?> 本图书已逾期，请尽快归还！
            </div>
            
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>图书名称</th>
                            <th>作者</th>
                            <th>借阅日期</th>
                            <th>应还日期</th>
                            <th>逾期天数</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($overdue_borrowings as $borrowing): ?>
                            <tr>
                                <td>
                                    <a href="book_detail.php?id=<?php echo $borrowing['book_id']; ?>">
                                        <?php echo htmlspecialchars($borrowing['title']); ?>
                                    </a>
                                </td>
                                <td><?php echo htmlspecialchars($borrowing['author']); ?></td>
                                <td><?php echo date('Y-m-d', strtotime($borrowing['borrow_date'])); ?></td>
                                <td><?php echo date('Y-m-d', strtotime($borrowing['return_date'])); ?></td>
                                <td>
                                    <?php 
                                    $return_date = strtotime($borrowing['return_date']);
                                    $today = time();
                                    $days_overdue = ceil(($today - $return_date) / (60 * 60 * 24));
                                    echo $days_overdue . ' 天';
                                    ?>
                                </td>
                                <td>
                                    <form method="post" action="" style="display: inline;">
                                        <input type="hidden" name="borrow_id" value="<?php echo $borrowing['borrow_id']; ?>">
                                        <button type="submit" name="return_book" class="btn btn-sm btn-danger" onclick="return confirm('确定要归还《<?php echo htmlspecialchars($borrowing['title']); ?>》吗？')">
                                            立即归还
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>
</div>

<?php include 'footer.php'; ?> 